let express = require('express');
let router = express.Router();
let app = express();
let server = require('http').createServer(app);
let io = require('socket.io')(server);
let sockets={};
let API = require('./api');
let n=0;
let socket_port=process.env.SOCKET_PORT;
io.on('connection', function(socket){
    socket.on("disconnect", function() {
        console.log("a user go out");
        --n;
        n<0?n=1:'';
        for(var i in sockets){
            //if(socket.id==sockets[i].id){  
            //}
    		sockets[i].send({
                type:'number',
                num:n
            });
    	}
    });
    socket.on('message', function(opt,callback){
        var id=opt.id;
        var time=opt.time;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
        if(sockets[id]){
            sockets[id].send({
                type:'repeated_login'
            });
        }  
        ++n;
        //socket.user_id=id;
        socket.time=time;     
        sockets[id]=socket;
        for(var i in sockets){
    		sockets[i].send({
                type:'number',
                num:n
            });
    	}
    })   
});


//接收php推送消息
router.post('/system_message', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    sockets[req.body.user_id].send(req.body);
    //res.send(req.body)
});

//开启端口监听socket
server.listen(socket_port);
module.exports = router;

